package com.wanxi.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.wanxi.dao.CompanyDao;
import com.wanxi.dao.Impl.CompanyDaoImpl;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.Company;
import com.wanxi.model.Teacher;
import com.wanxi.service.CompanyService;
import com.wanxi.util.JSONCopy;
import com.wanxi.util.RedisTool;
import com.wanxi.vo.CompanyVO;

import java.util.List;

public class CompanyServiceImpl implements CompanyService {
    CompanyDao companyDao=new CompanyDaoImpl();
    @Override
    public ResultDTO findCompany() {
        List<String> redisCompany = RedisTool.findToRedis("company");
//        判断redis中是否有数据
        if(redisCompany!=null){
//            返回redis中的数据,通过fastJson转换
            List<Company> list= JSON.parseObject(redisCompany.toString(), new TypeReference<List<Company>>() {});
            return ResultDTO.getDTO(list.size(),list.get(0));
        }
//        没有则从数据库中找数据
        Company company= Company.builder().id(1).build();
        Company c =companyDao.findCompanyById(company);
        if(c!=null){
//            将查到的数据放入redis
            RedisTool.putToRedis("company", JSON.toJSONString(c));
            return ResultDTO.getDTO(1,c);
        }
        return ResultDTO.builder().count(0).msg("error").code(1).build();
    }

    @Override
    public ResultDTO update(CompanyVO companyVO) {
        Company company= JSONCopy.copy(companyVO, Company.class);
        company.setId(1);
        int i=companyDao.update(company);
        if(i==1){
            RedisTool.deleteToRedis("company");
            return ResultDTO.getDTO(i,companyVO);
        }
        return ResultDTO.getDTO(0,companyVO);
    }
}
